<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Org\Code\Code;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

class LoginController extends CommonController
{
    //登录后台 方法及展示 页面
    public function login()
    {
        if($input = Input::all()) {
            $code = new Code();
            $_code = $code->get();
            if(strtoupper($input['code']) != $_code) {
                //return back()->with('msg', '验证码输入有误');
            }
            //两种方法实现登录
            //1.只适用于admin用户
            /*$user_info = User::firstOrFail();
            if( $user_info->user_name != $input['username'] || $user_info->password != md5(md5($input['password']).$user_info->salt) )
                return back()->with('msg', '用户名或密码错误');*/

            //2.通用密码验证方法 （根据用户名查找）
            $user_info = User::where('user_name', $input['username'])->first();
            if( !$user_info || $user_info->user_name != $input['username'] || $user_info->password != md5( md5($input['password']) . $user_info->salt ) ) {
                return back()->with('msg', '用户名或密码错误');
            }
            //登录成功
            session(['user' => $user_info]);
            //dd(session('user'));

            return redirect('admin/index');
        }else {
            //$info = DB::select('select * from blog_user WHERE user_id = ?',[1]);
            return view('admin.login');
        }
    }

    //验证码图片
    public function code()
    {
        $code = new Code();
        $code->make();
    }

    public function getcode()
    {
        //session(['name' => 'lisi']);
        $code = new Code();
        echo $code->get();

        //echo session('name');
    }

    //退出登录操作
    public function logout()
    {
        session(['user' => null]);
        return redirect('admin/login');
    }
}
